package com.tony.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: AutomicDemo001
 * @Auther: 皮蛋布丁
 * @Date: 2022/04/04/14:39
 * @Description: 原子操作类简介
 */
public class AutomicDemo001 {

    public static int money = 0;    //模拟银行存款
    public static AtomicInteger atomicMoney = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {

        int[] data = new int[]{100,200,300};    //要存款的总额

        /*for (int i = 0; i < data.length; i++) {
            final int temp = i; //为内部类使用
            new Thread(()->{
                money += data[temp];    //模拟存款
            }).start();

            TimeUnit.SECONDS.sleep(2);  //等待2秒时间
            System.out.println("计算完成，最终的存款总额为：" + money);
        }*/

        /*for (int i = 0; i < data.length; i++) { //进行存款线程的配置
            final int temp = i; //为内部类使用
            new Thread(()->{
                try {
                    TimeUnit.MILLISECONDS.sleep(100);   //100毫秒延迟
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                money += data[temp];    //模拟存款
            }).start();

        }
        TimeUnit.SECONDS.sleep(2);//等待2秒时间
        System.out.println("【计算完成】最终的存款总额：" + money);*/

        /*for (int i = 0; i < data.length; i++) { //进行存款线程的配置
            final int temp = i;
            new Thread(()->{
                try {
                    TimeUnit.MILLISECONDS.sleep(100);   //100毫秒延迟
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                save(data[temp]);
            }).start();
            TimeUnit.SECONDS.sleep(2);//等待2秒的时间
            System.out.println("【计算完成】最终的存款总额：" + money);
        }*/


        for (int i = 0; i < data.length; i++) {
            final int temp = i;
            new Thread(()->{
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                atomicMoney.addAndGet(data[temp]);
            }).start();
        }
        TimeUnit.SECONDS.sleep(2);
        System.out.println("计算完成，最终存款总额为：" +atomicMoney);



    }

    public static synchronized void save(int m) {
        money += m; //模拟存款
    }


}
